package com.atguigu.securitydemo1.service;


import com.atguigu.securitydemo1.entity.Users;
import com.atguigu.securitydemo1.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

//3.调用这个实现UserDetailsService接口的实体类进行用户名认证
@Component("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //TODO 这里在实际开发中,是查询的数据库信息

        //调用userMapper方法查询数据库
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
        queryWrapper.lambda().eq(Users::getUsername, username);
        Users users = usersMapper.selectOne(queryWrapper);

        //判断
        if (null == users) {
            //数据库没有用户名,认证失败
            // return null;
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //密码判断
        queryWrapper.lambda().eq(Users::getPassword, users.getPassword());
        Users usersByPassword = usersMapper.selectOne(queryWrapper);

        //判断
        if (usersByPassword == null) {
            throw new UsernameNotFoundException("密码错误!");
        }


        //基于角色或权限进行访问控制
        //2.在UserDetailsService,把返回User对象设置权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admins, Role_sale, ROLE_manager");

        //从查询数据返回user对象
        //这里返回的是spring的user对象
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()), authorities);

    }
}
